package com.qf.electronic.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.electronic.common.R;
import com.qf.electronic.common.ResponseStatus;
import com.qf.electronic.dto.LineDto;
import com.qf.electronic.dto.LineStateDto;
import com.qf.electronic.pojo.Line;
import com.qf.electronic.service.ILineService;
import com.qf.electronic.util.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wu
 * @since 2023-05-04
 */
@RestController
@RequestMapping("/line")
public class LineController {

    @Autowired
    private ILineService lineService;

    @Autowired
    private IdGenerator idGenerator;

    @PostMapping
    public R<Boolean> addLine(@Valid @RequestBody Line line, BindingResult result){
        if(result.hasFieldErrors()){
            return R.error(ResponseStatus.INVALID_PARAMETER);
        }
        line.setId(idGenerator.generateId(IdGenerator.LINE_PREFIX, IdGenerator.LINE_KEY, 11));
        return R.ok(lineService.save(line));
    }

    @PutMapping
    public R<Boolean> updateLine(@Valid @RequestBody Line line, BindingResult result){
        if(result.hasFieldErrors()){
            return R.error(ResponseStatus.INVALID_PARAMETER);
        }
        return R.ok(lineService.updateById(line));
    }

    @PutMapping("/state")
    public R<Boolean> changeLineState(LineStateDto stateDto){
        UpdateWrapper<Line> wrapper =new UpdateWrapper<>();
        wrapper.set("enable_status", stateDto.getState());
        wrapper.in("id", stateDto.getLineIds());
        return R.ok(lineService.update(wrapper));
    }

    @DeleteMapping
    public R<Boolean> deleteLines(@RequestParam("lineIds")List<String> lineIds){
        return R.ok(lineService.removeByIds(lineIds));
    }

    @GetMapping
    public R<Page<Line>> searchLines(LineDto lineDto){
        QueryWrapper<Line> wrapper = new QueryWrapper<>();
        String lineId = lineDto.getLineId();
        if(StringUtils.hasLength(lineId)){
            wrapper.eq("id", lineId);
        }
        String lineName = lineDto.getLineName();
        if(StringUtils.hasLength(lineName)){
            wrapper.eq("name", lineName);
        }
        Integer state = lineDto.getState();
        if(state != null){
            wrapper.eq("enable_status", state);
        }
        Page<Line> page = new Page<>(lineDto.getCurrentPage(), lineDto.getPageSize());
        return R.ok(lineService.page(page, wrapper));
    }
}

